package com.cj.media.utils

import android.app.*
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Build
import androidx.core.app.NotificationCompat

class NotificationUtil {
    companion object{

        private val NOTIFICATION_CHANNEL_ID = "com.cj.media.MediaService"
        private val NOTIFICATION_CHANNEL_NAME = "com.cj.media.channel_name"
        private val NOTIFICATION_CHANNEL_DESC = "com.cj.media.channel_desc"

        //开启通知，并申请成为前台服务
        @JvmStatic
        fun startNotification(service: Service,cls:Class<*>,iconRes:Int){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val notificationIntent = Intent(service, cls)

                val pendingIntent =
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                        PendingIntent.getActivity(
                            service,
                            0,
                            notificationIntent,
                            PendingIntent.FLAG_IMMUTABLE
                        )
                    } else {
                        PendingIntent.getActivity(
                            service,
                            0,
                            notificationIntent,
                            PendingIntent.FLAG_CANCEL_CURRENT
                        )
                    }
                val notificationBuilder = NotificationCompat.Builder(service, NOTIFICATION_CHANNEL_ID)
                    .setLargeIcon(
                        BitmapFactory.decodeResource(
                            service.resources,
                            iconRes
                        )
                    )
                    .setSmallIcon(iconRes)
                    .setContentTitle("Starting Service")
                    .setContentText("Starting monitoring service")
                    .setContentIntent(pendingIntent)
                val notification: Notification = notificationBuilder.build()
                val channel = NotificationChannel(
                    NOTIFICATION_CHANNEL_ID,
                    NOTIFICATION_CHANNEL_NAME,
                    NotificationManager.IMPORTANCE_DEFAULT
                )
                channel.description = NOTIFICATION_CHANNEL_DESC
                val notificationManager = service.getSystemService(Service.NOTIFICATION_SERVICE) as NotificationManager
                notificationManager.createNotificationChannel(channel)

                //申请成为前台应用
                service.startForeground(
                    1,
                    notification
                ) //必须使用此方法显示通知，不能使用notificationManager.notify，否则还是会报错误
                //java.lang.SecurityException: Media projections require a foreground service of type ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION
            }
        }

    }
}